package com.miguo.activity.base;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ViewFlipper;

import com.miguo.component.BaseHeadView;
import com.miguo.framework.web.CustomDownloadListener;
import com.miguo.framework.web.CustomWebChromeClient;
import com.miguo.framework.web.CustomWebView;
import com.miguo.framework.web.CustomWebViewClient;
import com.miguo.framework.web.IWebChromeClient;
import com.miguo.framework.web.IWebViewClient;
import com.miguo.ui.R;
import com.mrper.util.ApkUtil;

import java.util.ArrayList;
import java.util.List;


public abstract class BaseWebViewActivity extends BaseActivity implements OnClickListener,
        IWebChromeClient, IWebViewClient {

    public View mCustomView;
    public ProgressBar mProgressBar;
    public CustomWebView mWebView;
    public ViewFlipper mViewFlipper;

    private ImageView mNext;
    private ImageView mPre;
    private ImageView mFresh;
    private List<CustomWebView> mWebViews;
    private LinearLayout mNetworkError;

    private FrameLayout mFullscreenContainer;
    private CustomWebChromeClient.CustomViewCallback mCustomViewCallback;

    protected static BaseHeadView mBaseHead;
    protected LayoutInflater mInflater = null;
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    protected void initWebConfig() {
        mWebViews = new ArrayList<CustomWebView>();

        mPre = (ImageView) findViewById(R.id.web_pre);
        mNext = (ImageView) findViewById(R.id.web_next);
        mFresh = (ImageView) findViewById(R.id.web_fresh);
        mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);

        mPre.setOnClickListener(this);
        mNext.setOnClickListener(this);
        mFresh.setOnClickListener(this);

        mBaseHead = (BaseHeadView) findViewById(R.id.base_head);
        mBaseHead.setActivity(this);
        mBaseHead.setBackBtn(isBackBtn);
        //=============================== 2016-09-02 添加一下代码  ==============================
        mBaseHead.setOnInterceptImageBackEventListener(new BaseHeadView.OnInterceptImageBackEventListener() {
            @Override
            public boolean onInterceptImageBackEvent() {
                return isDealViewFlipperBackEvent();
            }
        });
        //================================ 2016-09-02 END =======================================

        mViewFlipper = (ViewFlipper) findViewById(R.id.ViewFlipper);
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    protected void initWebView() {
        initWebView(-1);
    }

    public void initWebView(int parentIndex) {

        RelativeLayout view = (RelativeLayout) mInflater.inflate(
                R.layout.webview, mViewFlipper, false);

        mWebView = (CustomWebView) view.findViewById(R.id.webview);

        mNetworkError = (LinearLayout) view.findViewById(R.id.network_error);
        mNetworkError.setOnClickListener(this);

        initializeCurrentWebView();

        synchronized (mViewFlipper) {
            if (parentIndex != -1) {
                mWebViews.add(parentIndex + 1, mWebView);
                mViewFlipper.addView(view, parentIndex + 1);
            } else {
                mWebViews.add(mWebView);
                mViewFlipper.addView(view);
            }
            mViewFlipper.setDisplayedChild(mViewFlipper.indexOfChild(view));
        }
    }

    protected void initializeCurrentWebView() {
        if (Build.VERSION.SDK_INT >= 11) {
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        mWebView.setWebViewClient(new CustomWebViewClient(this));
        mWebView.setDownloadListener(new CustomDownloadListener(this));
        mWebView.setWebChromeClient(new CustomWebChromeClient(this));
    }

    @Override
    public void onUrlLoading(String url) {
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        mProgressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        mProgressBar.setVisibility(View.GONE);
        upTitle();
    }

    @Override
    public void onReceivedError(WebView view, int errorCode,
                                String description, String failingUrl) {
        setWebError(true);
    }

    @Override
    public void onExternalApplicationUri(String uri) {
    }

    @Override
    public void onExternalApplicationUrl(String url) {
        try {
            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(i);
        } catch (Exception e) {
            // Notify user that the vnd url cannot be viewed.
            new AlertDialog.Builder(this)
                    .setTitle(R.string.VndErrorTitle)
                    .setMessage(
                            String.format(
                                    getResources().getString(
                                            R.string.VndErrorMessage), url))
                    .setPositiveButton(android.R.string.ok,
                            new AlertDialog.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                }
                            }).setCancelable(true).create().show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.web_pre:
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                }
                break;
            case R.id.web_next:
                if (mWebView.canGoForward()) {
                    mWebView.goForward();
                }
                break;
            case R.id.web_fresh:
            case R.id.network_error:
                if (mWebView.getVisibility() == View.GONE) {
                    setWebError(false);
                }
                freshBtnState(true);
                mWebView.reload();
                break;
        }
    }

    public void setHttpAuthUsernamePassword(String host, String realm,
                                            String username, String password) {
        if (mWebView != null) {
            mWebView.setHttpAuthUsernamePassword(host, realm, username,
                    password);
        }
    }

    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }


    private void setWebError(boolean error) {
        if (error) {
            mBaseHead.setTitle("找不到网页");
            mWebView.loadUrl("javascript:document.body.innerHTML=\"\"");
            mWebView.setVisibility(View.GONE);
            mNetworkError.setVisibility(View.VISIBLE);
        } else {
            mWebView.setVisibility(View.VISIBLE);
            mNetworkError.setVisibility(View.GONE);
        }
    }

    protected void upTitle() {
        String title = mWebView.getTitle();
        //去除空标题使用应用名称
//        if ((title != null) && (title.length() > 0)) {
//            if (null != mBaseHead.getTitleView() && !title.contains("taobao.com")) {
//                mBaseHead.setTitle(title);
//            }
//        } else {
//            clearTitle();
//        }

        if (!TextUtils.isEmpty(title)) {
            if (null != mBaseHead.getTitleView() && !title.contains("taobao.com") && !title.contains("tmall.com")) {
                mBaseHead.setTitle(title);
            }
        }
    }

    public void setTitleBarText(String title) {
        try {
            mBaseHead.setTitle(title);
        } catch (NullPointerException e) {
        }
    }

    private void clearTitle() {
        mBaseHead.setTitle(getResources().getString(R.string.app_name));
    }

    static class FullscreenHolder extends FrameLayout {

        public FullscreenHolder(Context ctx) {
            super(ctx);
                setBackgroundColor(ApkUtil.getColorById(ctx,android.R.color.black));
        }

        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }

    }

    @Override
    public void onHideCustomView() {
        if (mCustomView == null)
            return;

        setStatusBarVisibility(true);
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(mFullscreenContainer);
        mFullscreenContainer = null;
        mCustomView = null;
        mCustomViewCallback.onCustomViewHidden();
    }

    @Override
    public void onShowCustomView(View view, CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (mCustomView != null) {
            callback.onCustomViewHidden();
            return;
        }

        getWindow().getDecorView();
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        mFullscreenContainer = new FullscreenHolder(this);
        mFullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(mFullscreenContainer, COVER_SCREEN_PARAMS);
        mCustomView = view;
        setStatusBarVisibility(false);
        mCustomViewCallback = callback;
    }

    @Override
    public void onProgressChanged(WebView view, int progress) {
        mProgressBar.setProgress(progress);
    }

    @Override
    public void onCreateWindow(WebView view, boolean dialog,
                               boolean userGesture, Message resultMsg) {
        WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
        initWebView(mViewFlipper.getDisplayedChild());
        transport.setWebView(mWebView);
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        setTitleBarText(title);
    }

    @Override
    public void openFileChooser() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(
                Intent.createChooser(i,
                        getResources().getString(R.string.FileChooserPrompt)),
                2);
    }

    @Override
    public void initSelected() {
        if (mWebView.canGoBack()) {
            mPre.setSelected(false);
            mPre.setClickable(true);
        } else {
            mPre.setSelected(true);
            mPre.setClickable(false);
        }
        if (mWebView.canGoForward()) {
            mNext.setSelected(false);
            mNext.setClickable(true);
        } else {
            mNext.setSelected(true);
            mNext.setClickable(false);
        }
    }

    @Override
    public void freshBtnState(boolean isfresh) {
        if (isfresh) {
            mFresh.setSelected(true);
            mFresh.setClickable(false);
            return;
        }
        mFresh.setSelected(false);
        mFresh.setClickable(true);
    }

    @Override
    protected void onDestroy() {
        mWebView.cancelLongPress();
        mWebView.clearHistory();
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        if (mWebView != null) {
            mWebView.doOnPause();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (mWebView != null) {
            mWebView.doOnResume();
        }
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onBackPressed() {
        overridePendingTransition(0, R.anim.push_right_out);
        this.finish();
        super.onBackPressed();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                mWebView.goForward();
                break;
            case KeyEvent.KEYCODE_VOLUME_UP:
                mWebView.goBack();
                break;
            case KeyEvent.KEYCODE_BACK:
                /**********  2016.09.02 添加一下代码 ********************/
                if (isDealViewFlipperBackEvent()) return true;
                /*************   2016.09.02 end  ***************************/

                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    this.onBackPressed();
                }
                break;
        }
        return false;
    }

    /**  处理ViewFlipper中WebView的返回事件  **/
    private boolean isDealViewFlipperBackEvent() {
        int size = mWebViews.size();
        if(size > 0) {
            if (size > 1) {
                int maxIndex = size - 1;
//                if(isItemWebViewCanGoBack(maxIndex)) return true;
                mViewFlipper.setDisplayedChild(mViewFlipper.indexOfChild(mWebViews.get(maxIndex - 1)));
                mViewFlipper.removeViewAt(maxIndex);
                mWebViews.remove(maxIndex);
                return true;
            }else {
                if(isItemWebViewCanGoBack(0)) return true;
            }
        }
        return false;
    }

    /***  ItemWebView是否有历史记录  **/
    private boolean isItemWebViewCanGoBack(int index) {
        WebView itemWebView = mWebViews.get(index);
        if (itemWebView.canGoBack()) {
            itemWebView.goBack();
//            mViewFlipper.setDisplayedChild(mViewFlipper.indexOfChild(mWebViews.get(index)));
            return true;
        }
        return false;
    }

}
